from ninja.security import HttpBearer
import jwt
from datetime import datetime, timedelta
from typing import Optional
from ninja.security import HttpBearer

from chat.models import ChatUser


SECRET_KEY = 'your-secret-key'
ALGORITHM = 'HS256'

class AuthBearer(HttpBearer):
    def authenticate(self, request, token: str) -> Optional[dict]:
        """认证jwt
        Returns:
            返回后数据保存在request.auth
        """
        try:
            # 解码并验证JWT
            payload = jwt.decode(
                token,
                SECRET_KEY,
                algorithms=[ALGORITHM],
                options={'verify_exp': True},  # 根据需要设置是否检查过期时间
            )
            
            if 'user_id' in payload:
                return ChatUser.objects.get(id=payload['user_id'])
            
            return None

        except (jwt.exceptions.PyJWTError, ValueError):  # 包括但不限于DecodeError、ExpiredSignatureError等异常
            return None


# 在你的应用程序中，你可能还需要一个生成JWT的函数
def create_jwt_token(user_id: int) -> str:
    payload = {
        'user_id': user_id,
        'exp': datetime.utcnow() + timedelta(minutes=30),  # 设置JWT有效期为30分钟
    }
    return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)